package loadiconhandler

import (
	"fmt"
	"gmap-backend/internal/config"
	"gmap-backend/internal/server/vo"
	"gmap-backend/internal/util/pathutil"
	"strings"
)

type DirOpenByLoadIcon struct {
}

func (owner *DirOpenByLoadIcon) CanHandle(appConfig *config.AppConfig, req *vo.PathReq) (bool, any) {
	urlMatch := strings.HasPrefix(req.Path, "diropenby:///") || strings.HasPrefix(req.Path, "diropenby://")
	if !urlMatch {
		return false, nil
	}
	parts := strings.Split(strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(req.Path, "diropenby:///"), "diropenby://")), "@@")
	if len(parts) < 2 {
		panic("diropenby协议格式有误")
	}
	dir, opener := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])
	if "" == dir || "" == opener {
		panic("diropenby协议格式有误")
	}
	return true, []string{dir, opener}
}

func (owner *DirOpenByLoadIcon) Handle(appConfig *config.AppConfig, req *vo.PathReq, extra any) *vo.LoadIconResp {
	parts := extra.([]string)
	dir, opener := parts[0], parts[1]

	dirParseResult := pathutil.ParseValidPath(dir, req.CtxDir)
	if !dirParseResult.Succ || dirParseResult.File {
		panic(fmt.Sprintf("目录不存在，无法打开：\r\n%s", dir))
	}
	bigImgPath := SPECIAL_PATH_FOLDER

	// 打开方式判断：
	smallImgPath := ""
	// photo - 图片查看器
	// 带有% - 命令脚本
	// 否则按文件路径处理，图标从文件中提取
	if "photo" == opener {
		smallImgPath = SPECIAL_PATH_PHOTO
	} else if strings.Contains(opener, "%1") {
		smallImgPath = SPECIAL_PATH_CMD
	} else {
		openerParseResult := pathutil.ParseValidPath(opener, "")
		if !openerParseResult.Succ || openerParseResult.Dir {
			panic(fmt.Sprintf("打开方式不存在，无法打开：\r\n%s", opener))
		}
		smallImgPath = GetFileIconUrl(appConfig, openerParseResult.ValidPath).Url
	}
	return &vo.LoadIconResp{
		Cascade: true,
		Url:     bigImgPath,
		Url2:    smallImgPath,
	}
}
